package com.shelpe.services.sinbadgateway.configuration;

import java.util.Map;

import org.springframework.boot.context.embedded.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@EnableWebMvc
@Configuration
public class WebConfiguration {
	
	@Bean
	public WebMvcConfigurer corsConfigurer() {
		return new WebMvcConfigurerAdapter() {
			@Override
			public void addCorsMappings(CorsRegistry registry) {
				registerCors(registry);
			}
		};
	}
	
	@Bean
	public FilterRegistrationBean corsFilter() {
	    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
	    
	    LocalCorsRegistry registry = new LocalCorsRegistry();
	    this.registerCors(registry);
	   
	    registry.toSource(source);
	    FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
		bean.setOrder(-200);
		return bean;
	}
	
	private void registerCors(CorsRegistry registry){
		registry.addMapping("/**")
		.allowedOrigins("http://dev.shelpe.com","http://master.shelpe.com","http://simba.shelpe.com", "http://sinbad.shelpe.com", "http://company.shelpe.com")
        .allowedMethods("PUT", "DELETE","GET", "POST", "OPTION")
        .allowedHeaders("Accept-Encoding", "Accept-Language", "Cache-Control", "Connection", "Host", "Origin", "Pragma",
        		"Content-Type", "Referer", "User-Agent", "Access-Control-Request-Headers", "Access-Control-Request-Method",
        		"accept", "Authorization")
        .exposedHeaders("Access-Control-Allow-Origin", "Access-Control-Allow-Credentials")
        .allowCredentials(true).maxAge(3600);
	}
	
	public static class LocalCorsRegistry extends CorsRegistry{
		
		public void toSource(UrlBasedCorsConfigurationSource source){
			for(Map.Entry<String, CorsConfiguration> entry:super.getCorsConfigurations().entrySet()){
				source.registerCorsConfiguration(entry.getKey(), entry.getValue());
			}
		}
		
	}
}
